package com.segersten.kalaha;

import java.util.logging.Logger;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

public class Channel {
	
	private static Logger LOG = Logger.getLogger(Channel.class.getCanonicalName());

	public static String createToken(Player player) {
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		return channelService.createChannel(player.getUserId());
	}
	
	private static void sendUpdateToUser(Player player, String message) {
		String channelKey = null;
		try {
		if (player != null && player.getChannelToken()!=null) {
			ChannelService channelService = ChannelServiceFactory.getChannelService();
			channelKey = player.getUserId();
			channelService.sendMessage(new ChannelMessage(channelKey, message));
			//LOG.severe("Wrote to channel - " + channelKey + " - '" + message + "'");
		}
		} catch(Exception e ) {
			//e.printStackTrace();
			Logger.getLogger(Channel.class.getCanonicalName()).severe("Failed to send message to " + 
					player.getUserId() +" using token "+ channelKey +" reason " + e.getLocalizedMessage());
		}
	}

	public static void sendUpdateToClients(String message, Player... players) {
		for (Player p : players) {
			sendUpdateToUser(p, message);
		}
	}

}
